import {Page} from '@/base/Page';
import {Info} from '@/base/model/Info';
import {deleteInfo, getInfoList, putInfoEnable} from '@/base/api/InfoApi';
import {infoBloc} from '@/store/module/Info';

class Form {
  title = '';
  companyId = [];
}

export class SortBloc {
  form = new Form();

  paged: Page<Info> = new Page<Info>([], 0, 1, 15, 0, []);
  loading = false;
  sortId = 0;

  load(pageIndex: number, pageSize: number) {
    this.loading = true;
    const obj: any = {
      pageIndex,
      pageSize,
      title: this.form.title,
      companyId: this.form.companyId
    };
    if (this.sortId !== 0) obj.sortId = this.sortId;
    return getInfoList(obj).then(res => {
      this.paged = res.data;
    }).finally(() => {
      this.loading = false;
    });

  }

  search() {
    this.sortId = 0;
    infoBloc.getSortId(this.sortId);
    this.load(1, 15)
  }

  removeItem(dateItem: Info) {
    this.loading = true;
    return deleteInfo(dateItem.id)
      .finally(() => {
        this.loading = false;
      });
  }

  reset() {
    this.form.title = '';
    this.form.companyId = [];
    this.paged.pageIndex = 1;
    this.paged.pageSize = 15;
    this.load(this.paged.pageIndex, this.paged.pageSize);
  }

  getCompanyName(companyId: number) {
    const item = this.paged.extras.find(x => x.id === companyId);
    return item == null ? '' : item.name;
  }

  modifyEnable(val: Info) {
    this.loading = true;
    putInfoEnable({id: val.id, enable: val.enable}).finally(() => {
      this.loading = false;
      this.load(this.paged.pageIndex, this.paged.pageSize);
    });
  }

}
